package com.zl.init;


import com.zl.framework.scm.client.SCMConfiguration;
import com.zl.framework.util.CommonConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.MutablePropertyValues;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;


@Component
public class DBinitBeanDefinitionRegistryPostProcessor implements BeanDefinitionRegistryPostProcessor {

    Logger logger = LoggerFactory.getLogger(this.getClass());

    public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException
    {
        //移除原来的bean
        registry.removeBeanDefinition("propertyPlaceholderConfigurer");

        //代理zookeeper
        logger.info("代理zookeeper-start");
        BeanDefinition beanDefinition = registry.getBeanDefinition("com.alibaba.dubbo.config.RegistryConfig");
        MutablePropertyValues mutablePropertyValues = beanDefinition.getPropertyValues();
        String address = (String) mutablePropertyValues.get("address");
        String zookeeperIp = address.split(":")[0];
        String zookeeperPort = address.split(":")[1];
        CommonConfig.DUBBO_ZOOKEEPER_ADDRESS = "127.0.0.1:" + zookeeperPort;
        String configFilePath = "/scm.properties";
        SCMConfiguration.getInstance(configFilePath);
        SCMConfiguration scmConfiguration = SCMConfiguration.configs.get(configFilePath);
        try {
            Field field = SCMConfiguration.class.getDeclaredField("zkServer");
            field.setAccessible(true);
            field.set(scmConfiguration, CommonConfig.DUBBO_ZOOKEEPER_ADDRESS);
        } catch (Exception e) {
            e.printStackTrace();
        }
        address = address.replace(zookeeperIp, "127.0.0.1");
        SSHDBUtil.initDB(zookeeperIp, Integer.valueOf(zookeeperPort), Integer.valueOf(zookeeperPort));
        mutablePropertyValues.addPropertyValue("address", address);

        logger.info("代理zookeeper-end");
    }

    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException
    {

    }
}
